import React, { useEffect, useRef, useState } from 'react'
import styles from './index.module.scss'
import {
  Card,
  Breadcrumb,
  Form,
  Input,
  Button,
  Space,
  Upload,
  Radio,
  message,
} from 'antd'
import { Link, useParams } from 'react-router-dom'
// import { useChannels } from '@/hooks'
import MyChannel from '@/components/MyChannel.js'

import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import { PlusOutlined } from '@ant-design/icons'
import { useDispatch } from 'react-redux'
import {
  addArticle,
  editArticle,
  getArticleDetail,
} from '@/store/actions/article'
import { useHistory } from 'react-router-dom'

export default function Publish() {
  // const channels = useChannels()
  const dispatch = useDispatch()
  const history = useHistory()

  //处理编辑的情况，编辑需要回显
  const { id } = useParams()
  console.log(id, 3232)

  useEffect(() => {
    //发送请求
    if (id) {
      dispatch(getArticleDetail(id)).then((res) => {
        console.log(res, 42)

        formRef.current.setFieldsValue({
          ...res,
          type: res.cover.type,
        })

        setType(res.cover.type)

        const images = res.cover.images.map((item) => {
          return {
            url: item,
          }
        })

        setFileList(images)
        fileRef.current = images
      })
    }
  }, [id, dispatch])

  const [fileList, setFileList] = useState([
    // {
    //   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
    // },
  ])

  const fileRef = useRef(fileList)
  const formRef = useRef(null)

  const [type, setType] = useState(1)

  //上传图片
  const onChange = ({ fileList }) => {
    setFileList(fileList)
    fileRef.current = fileList
    // console.log(fileRef.current)
    //当前文件数量变化 都可以重新校验
    formRef.current.validateFields(['type'])
  }

  //控制 封面数量
  const onTypeChange = (e) => {
    // console.log(e.target)
    const count = e.target.value
    setType(count)
    setFileList(fileRef.current.slice(0, count))
  }

  //处理提交
  const add = async (draft, values) => {
    console.log(values, 5454)
    const { type, ...rest } = values

    //遍历fileList进行格式处理
    const images = fileList.map((item) => {
      if (item.url) {
        return item.url
      } else {
        return item.response.data.url
      }
    })
    const data = {
      ...rest,
      cover: {
        type,
        images: images,
      },
    }
    console.log(data)

    if (id) {
      await dispatch(editArticle(draft, { ...data, id }))
    } else {
      await dispatch(addArticle(draft, data))
    }

    message.success('发布成功', 1, () => {
      history.push('/home/article')
    })
  }
  //处理发布
  const handleFinish = async (values) => {
    add(false, values)
  }

  //处理草稿
  const addDraft = async () => {
    const values = await formRef.current.validateFields()
    add(true, values)
  }

  return (
    <div className={styles.root}>
      <Card
        title={
          <Breadcrumb separator="/">
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>{id ? '编辑' : '发布'}文章</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          onFinish={handleFinish}
          ref={formRef}
          initialValues={{
            title: '',
            channel_id: null,
            content: '',
            type: 1,
          }}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          size="large"
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[
              {
                required: true,
                message: '标题不能为空',
              },
            ]}
          >
            <Input
              placeholder="请输入文章的标题"
              style={{ width: 400 }}
            ></Input>
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[
              {
                required: true,
                message: '频道不能为空',
              },
            ]}
          >
            <MyChannel></MyChannel>
          </Form.Item>
          <Form.Item
            label="封面"
            name="type"
            rules={[
              {
                validator(_, value) {
                  if (value !== fileList.length) {
                    return Promise.reject(new Error(`请上传${value}张图片`))
                  } else {
                    return Promise.resolve()
                  }
                },
              },
            ]}
          >
            <Radio.Group value={type} onChange={onTypeChange}>
              <Radio value={1}>单图</Radio>
              <Radio value={3}>三图</Radio>
              <Radio value={0}>无图</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4, span: 20 }}>
            <Upload
              listType="picture-card"
              fileList={fileList}
              name="image"
              action={`${process.env.REACT_APP_URL}/upload`}
              onChange={onChange}
              maxCount={type}
            >
              {fileList.length < type && <PlusOutlined />}
            </Upload>
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[
              {
                required: true,
                message: '内容不能为空',
              },
            ]}
          >
            <ReactQuill></ReactQuill>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4, span: 20 }}>
            <Space>
              <Button type="primary" htmlType="submit">
                {id ? '编辑' : '发布'}文章
              </Button>
              <Button onClick={addDraft}>存入草稿</Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
